<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-form ref="searchForm" :model="searchForm" :inline="true" label-width="120px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model.trim="searchForm.username" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model.trim="searchForm.email" />
      </el-form-item>
      <el-form-item label="角色" prop="roles">
        <el-select v-model="searchForm.roles" clearable placeholder="请选择">
          <el-option v-for="item in introOption" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-button type="primary" @click="onSubmit">搜索</el-button>
      <el-button @click="onCancel">取消</el-button>
    </el-form>
    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label="ID" width="95">
        <template slot-scope="scope">
          {{ scope.$index + 1 + (pagination.pageNumber - 1) * pagination.pageSize }}
        </template>
      </el-table-column>
      <el-table-column label="用户名">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="邮箱">
        <template slot-scope="scope">
          {{ scope.row.email }}
        </template>
      </el-table-column>
      <el-table-column label="角色">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.roles"
            :disabled="scope.row.disabled"
            placeholder="请选择"
            @change="roleChange(scope.row._id, scope.row.roles)"
          >
            <el-option
              v-for="item in introOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" label="更新日期" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.updatedAt }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="scope.row.disabled = !scope.row.disabled">
            {{ scope.row.disabled ? '设置角色' : '取消设置' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block">
      <el-pagination
        background
        :current-page.sync="pagination.pageNumber"
        :page-size="pagination.pageSize"
        layout="total, prev, pager, next"
        :total="pagination.total"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { getUserList, changeRole } from '@/api/user'
import { mapGetters, mapMutations } from 'vuex'
export default {
  name: 'Users',
  data() {
    return {
      list: [],
      listLoading: false,
      introOption: [
        {
          value: 'admin',
          label: '管理员'
        },
        {
          value: 'editor',
          label: '编辑人员'
        }
      ],
      searchForm: {
        username: '',
        email: '',
        roles: ''
      },
      pagination: {
        total: 0,
        pageSize: 5,
        pageNumber: 1
      }
    }
  },
  computed: {
    ...mapGetters(['name'])
  },
  created() {
    this.fetchData()
  },
  methods: {
    ...mapMutations('user', ['SET_ROLES']),
    async roleChange(id, roles) {
      if (roles === '') {
        this.$message({
          type: 'error',
          message: '角色不能为空'
        })
        return
      }
      try {
        const response = await changeRole({ id, roles })
        this.$message({
          type: 'success',
          message: '角色更新成功'
        })
        if (this.name === response.data.username) {
          this.SET_ROLES([])
          this.$router.push('/dashboard').catch(() => {})
        } else {
          this.fetchData()
        }
      } catch (error) {
        console.log('error: ', error)
      }
    },
    onSubmit() {
      var searchForm = this.searchForm
      console.log('searchForm: ', searchForm)
      this.fetchData(searchForm)
    },
    onCancel() {
      this.$refs.searchForm.resetFields()
    },
    // 选择页码
    handleCurrentChange(val) {
      this.pagination.pageNumber = val
      this.fetchData(this.searchForm)
    },
    // 拉表格数据
    async fetchData(searchForm = {}) {
      var { pageSize, pageNumber } = this.pagination
      this.listLoading = true
      try {
        const response = await getUserList({ pageSize, pageNumber, ...searchForm })
        const data = response.data
        data.forEach((item) => {
          item.disabled = true
        })
        console.log('data: ', data)
        this.list = data

        this.listLoading = false
        this.pagination = response.pagination
      } catch (error) {
        console.log('error: ', error)
        this.listLoading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.block {
  margin-top: 20px;
  text-align: center;
}
</style>
